package com.demo.unittest.springweb.controller;

import com.demo.unittest.springweb.bean.JSONResponse;
import com.demo.unittest.springweb.bean.User;
import com.demo.unittest.springweb.service.UserService;
import com.demo.unittest.springweb.util.DateUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 测试两种mock注入
 * 测试logger
 * 测试mock Request
 * 测试mock DB
 *
 * @author tzp
 * @since 2018/4/28
 */
@RestController
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    /**
     * post请求
     * 响应JSON对象
     */
    @PostMapping("/login")
    public JSONResponse login(
            HttpServletRequest request,
            @RequestParam("name") String name,
            @RequestParam("password") String password
    ) {
        User user = userService.authenticateUser(name, password);
        String date = DateUtil.dateToStr(new Date());
        if (user != null) {
            logger.info("user login: {}", name);
            return new JSONResponse(0, "login success", user);
        } else {
            return new JSONResponse(1, "login fail", date);
        }
    }

    /**
     * get请求
     * 直接向响应中写出
     */
    @GetMapping("/hello")
    public void writeToResponse(
            HttpServletResponse response,
            @RequestParam("name") String name
    ) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Custom-Header", "Custom-Header-Value");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.print("Hello " + name);
            outputStream.flush();
            logger.info("user hello: {}", name);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
    }
}
